<?php
Yii::import('ext.feed.*');
class SiteController extends Controller
{
    public $layout = '//layouts/main';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	public function actions(){
    return array(
        'captcha'=>array(
            'class'=>'CaptchaExtendedAction',
        ),
    );
  }

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('error', 'logout', 'index', 'history', 'vision', 'contact', 'terms', 'privacy', 'news', 'forgot', 'captcha', 'subscribeCreate'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('index','create','update'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError()
	{
	    if($error=Yii::app()->errorHandler->error)
	    {
	    	if(Yii::app()->request->isAjaxRequest)
	    		echo $error['message'];
	    	else
	        	$this->render('error', $error);
	    }
	}

  public function actionForgot()
  {
    $user = new Users;

    if(isset($_POST['Users']))
    {
      $data = $_POST['Users'];
      $valid = Users::model()->find('username = :username AND email = :email', array(':username' => $data['username'], ':email' => $data['email']));

      if(isset($valid))
      {
        // generate password
        for($code_length = 10, $newcode = ''; strlen($newcode) < $code_length; $newcode .= chr(!rand(0, 2) ? rand(48, 57) : (!rand(0, 1) ? rand(65, 90) : rand(97, 122))));

        $email = Yii::app()->email;
        $email->to = $data['email'];
        $email->subject = 'ACSI - Your reset password';
        $email->message = 'Our system automatically created a new password for you. Please use this login information the next time you login.
          Username: '.$_POST['Users']['username'].'
          Password: '.$newcode.'
          You should change this password the next time you login. You can change your password in the account settings. ';
        $email->send();

        Yii::app()->user->setFlash('success', 'Success');
        Yii::app()->user->setFlash('content', 'A reset email has been sent to your email.');
        $this->redirect(bu(''));
      }
    }

    $this->render('forgot',array(
      'user' => $user,
    ));
  }

    public function actionIndex()
    {
      $session = new CHttpSession;
      $session->open();

      Yii::app()->counter->refresh();

      $member_id = '0';
      $news = News::model()->findAll('member_id = :member_id AND published = 1 order by level DESC, created_at DESC, modified_at DESC LIMIT 10', array(':member_id' => $member_id));
      $articles = Articles::model()->findAll('member_id = :member_id AND published = 1 order by level DESC, created_at DESC, modified_at DESC LIMIT 3', array(':member_id' => $member_id));
      //$links = Links::model()->findAll('member_id = :member_id order by created_at DESC', array(':member_id' => $member_id));

      $criteria = new CDbCriteria;
      $criteria->order = "created_at";
      $criteria->limit = 3;
      $banners = Banners::model()->findAll($criteria);

      //Set into 1 array
      //news
      $count = 0;

	  //articles
      $x=0;
      foreach($articles as $article)
      {
        $count ++;
        $isi[$count]['offset'] = $x;
        $isi[$count]['id'] = $article->id;
        $isi[$count]['created_at'] = $article->created_at;
        $isi[$count]['type'] = 'articles';
        $temp[$count] = $article->created_at;
        $x ++;
      }

      $x=0;
      foreach($news as $n)
      {
        $count ++;
        $isi[$count]['offset'] = $x;
        $isi[$count]['id'] = $n->id;
        $isi[$count]['created_at'] = $n->created_at;
        $isi[$count]['type'] = 'news';
        $temp[$count] = $n->created_at;
        $x++;
      }

      /*
      //links
      $x=0;
      foreach($links as $link)
      {
        $count ++;
        $isi[$count]['offset'] = $x;
        $isi[$count]['id'] = $link->id;
        $isi[$count]['created_at'] = $link->created_at;
        $isi[$count]['type'] = 'links';
        $isi[$count]['url'] = $link->url;
        $temp[$count] = $link->created_at;
        $x++;
      }
      */

      //sort order_by created_at
      //arsort($isi);
      Helpers::array_sort($isi, 'created_at', 'SORT_DESC');
      $count = count($isi);
      $max = 15;
      for($a=$count;$a>$max;$a--)
      {
        array_pop($isi);
      }

      //shortcuts
      $cedp = "Seminar dua hari yang akan membekali para pendidik Kristen dengan pengetahuan, ketrampilan, dan sikap hati dalam menanggapi informasi terbaru seputar dunia pendidikan berbasis Kekristenan. Seminar ini bukan hanya diperuntukkan bagi para guru saja, tetapi bagi semua orang yang bersentuhan dengan dunia pendidikan Kristen termasuk pengurus yayasan dan para orang tua murid yang peduli dengan pendidikan anak - anak mereka.";
      $ode = "Seminar dua hari yang akan membekali para pendidik Kristen dengan pengetahuan, ketrampilan, dan sikap hati dalam menanggapi informasi terbaru seputar dunia pendidikan berbasis Kekristenan. Seminar ini bukan hanya diperuntukkan bagi para guru saja, tetapi bagi semua orang yang bersentuhan dengan dunia pendidikan Kristen termasuk pengurus yayasan dan para orang tua murid yang peduli dengan pendidikan anak - anak mereka.";
      $cec = "CEC - M. Ed (Christian Educator Certification - Master of Education) Program merupakan pengembangan dari program sertifikasi pendidik Kristen ACSI yang sudah berjalan mulai tahun 2005. Program CEC-M. Ed yang diluncurkan pertama kali pada bulan Februari 2010 merupakan kolaborasi ACSI Indonesia dengan Southland College New South Wales Australia (www.southland.edu.au) di mana modul - modul yang termasuk dalam program sertifikasi ACSI dihargai separuh dari kredit yang harus dipenuhi untuk mendapatkan gelar Master of Education in Education Leadership dari Southland Collage.";
      $activities = "SELC (Student English Leadership Conference) adalah program yang diadakan selama tiga hari empat malam bagi siswa kelas 8 sampai 11 dan mentor dengan menggunakan bahasa Inggris sebagai pengantarnya. Program ini adalah kerjasama ACSI Indonesia dengan Cedarville University dari Ohio, USA (www.cedarville.edu).";
      $forum = "ACSI Forum merupakan bentuk pelayanan ACSI kepada sekolah-sekolah anggota di berbagai kota di Indonesia. Sebuah pertemuan para Pendidik Kristen yang mengakomodasikan kebutuhan sekolah untuk membahas perkembangan pendidikan Kristen.";
      $cciht = "CEC - M. Ed (Christian Educator Certification - Master of Education) Program merupakan pengembangan dari program sertifikasi pendidik Kristen ACSI yang sudah berjalan mulai tahun 2005. Program CEC-M. Ed yang diluncurkan pertama kali pada bulan Februari 2010 merupakan kolaborasi ACSI Indonesia dengan Southland College New South Wales Australia (www.southland.edu.au) di mana modul - modul yang termasuk dalam program sertifikasi ACSI dihargai separuh dari kredit yang harus dipenuhi untuk mendapatkan gelar Master of Education in Education Leadership dari Southland Collage. ";


      $this->render('index', array(
        'news' => $news,
        'articles' => $articles,
        //'links' => $links,
        'isi' => $isi,
        'temp' => $temp,
        'banners' => $banners,

        'cedp' => $cedp,
        'ode' => $ode,
        'cec' => $cec,
        'activities' => $activities,
        'forum' => $forum,
        'cciht' => $cciht,
      ));
      //*/
    }


    public function actionHistory()
    {
        $this->render('history');
    }

    public function actionVision()
    {
        $this->render('vision');
    }

    public function actionTerms()
    {
        $this->render('terms');
    }

    public function actionPrivacy()
    {
        $this->render('privacy');
    }

    public function actionNews()
    {
      if(isset($_GET['member']))
      {
        $member_id = $_GET['member'];
      }
      else
      {
        $member_id = 0;
      }

			$subscribe = new Subscribes;
      $user = new Users;

      $news = News::model()->findAll('member_id = :member_id AND published = 1 order by level DESC, created_at DESC, modified_at DESC LIMIT 2', array(':member_id' => $member_id));
      $articles = Articles::model()->findAll('member_id = :member_id AND published = 1 order by level DESC, created_at DESC, modified_at DESC LIMIT 2', array(':member_id' => $member_id));
      $links = Links::model()->findAll('member_id = :member_id AND published = 1 order by level DESC, created_at DESC, modified_at DESC LIMIT 7', array(':member_id' => $member_id));
      $this->render('news_contents',array(
        'news' => $news,
        'articles' => $articles,
        'links' => $links,
				'subscribe' => $subscribe,
        'user' => $user,
      ));
    }

    public function actionSubscribeCreate()
    {
      $model=new Subscribes;

      if(isset($_POST['Subscribes']))
      {
        $check = Users::model()->find('email = :email', array(':email' => $_POST['Subscribes']['email']));

        if(!$check)
        {
          $model->attributes=$_POST['Subscribes'];

          if($model->save())
          {
            Yii::app()->user->setFlash('success', 'Success');
            Yii::app()->user->setFlash('content', 'You have successfully subscribe to our newsletter.');

            $this->redirect(bu("site/news"));
          }
          else
          {
            $errors = $model->getErrors();
            $content = '';

            foreach($errors as $error ){
              $content = $content.$error[0].'<br />';
            }

            Yii::app()->user->setFlash('error', 'Error');
            Yii::app()->user->setFlash('content', $content);
            $this->redirect(bu("site/news"));
          }
        }
        else
        {
          Yii::app()->user->setFlash('error', 'Error');
          Yii::app()->user->setFlash('content', 'Email address already exist in database!');

          $this->redirect(bu("site/news"));
        }
      }
    }
}